package me.ezitku.base.extensions.Notification

import android.app.*
import android.app.Notification.Builder
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.drawable.Icon
import android.media.AudioAttributes
import android.net.Uri
import android.os.Build
import android.os.Environment
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import android.widget.RemoteViews
import com.pawegio.kandroid.notificationManager
import java.io.File
import java.lang.Exception
import java.lang.NullPointerException


fun Context.createNotificationGroup(groupId: String, groupName: String) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val group = NotificationChannelGroup(groupId, groupName)
        notificationManager?.createNotificationChannelGroup(group)
    }
}

/**
 * @param importance NotificationManager.IMPORTANCE_DEFAULT
 */

class NotifivationChannelModel {
    var sound: Uri? = null
}

fun Context.createNotificationChannel(channelId: String, channeName: String, action: NotifivationChannelModel.(channel: NotificationChannel) -> Unit) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        createNotificationChannel(channelId, channeName, NotificationManager.IMPORTANCE_DEFAULT, action)
    }
}

fun Context.createNotificationChannel(channelId: String, channeName: String, importance: Int, action: NotifivationChannelModel.(channel: NotificationChannel) -> Unit) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val channel = NotificationChannel(channelId, channeName, importance)
        val model = NotifivationChannelModel()
        action(model, channel)
        notificationManager?.createNotificationChannel(channel)
    }
}


//fun Context.createNotificationChannel(channelId: String, channeName: String,importance: Int) {
//    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//        val channel = NotificationChannel(channelId, channeName, NotificationManager.IMPORTANCE_DEFAULT)
//        notificationManager?.createNotificationChannel(channel)
//    }
//}


@RequiresApi(Build.VERSION_CODES.JELLY_BEAN)
fun Context.createNotification(smallIcon: Int, notifyId: Int, channelId: String, action: NotificationModel.(Builder) -> Unit): NotificationManager {


    val manager = notificationManager

    val mBuilder: Builder
//    val mBuilder = NotificationCompat.Builder(this, channelId)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        mBuilder = Builder(this, channelId)
    } else {
        mBuilder = Builder(this)
        //设置通知方式，声音，震动，呼吸灯等效果，这里通知方式为声音
        mBuilder.setDefaults(Notification.DEFAULT_LIGHTS)
    }
    //设置最小图标
    mBuilder.setSmallIcon(smallIcon)

    val model = NotificationModel()
    action(model, mBuilder)


    //region 设置自定义 UI 的话
    if (model._layoutId != 0) {
        val remoteView = RemoteViews(packageName, model._layoutId)
        model._remoteView = remoteView
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            mBuilder.setCustomContentView(remoteView)
        } else {
            mBuilder.setContent(remoteView)
        }


        model._bindProgress.forEach {
            remoteView.setProgressBar(it.key, it.value.max, it.value.progress, it.value.indeterminate)
        }
        model._bindTexts.forEach {
            val i = it.key
            val s = it.value
            remoteView.setTextViewText(i, s)
        }
        model._bindImages.forEach {
            val i = it.key
            val image = it.value
            when (image) {
                is Int -> {
                    remoteView.setImageViewResource(i, image)
                }
                is Uri -> {
                    remoteView.setImageViewUri(i, image)
                }
                is Bitmap -> {
                    remoteView.setImageViewBitmap(i, image)
                }

            }

        }

        model._bindClicks.forEach {
            val i = it.key
            val pendingIntent = it.value
            remoteView.setOnClickPendingIntent(i, pendingIntent)
        }


    }

    //点击后自动删除通知
    mBuilder.setAutoCancel(model.autoCancel)
    val notification = mBuilder.build()
    if (model.noClear) {
        notification.flags = Notification.FLAG_NO_CLEAR
    } else {
        notification.flags = Notification.FLAG_AUTO_CANCEL
    }
    /**
     * 设置FLAG_ONGOING_EVENT
     * 该 flag 表示发起正在运行事件（活动中）
     * //设置 Notification 的 flags = FLAG_NO_CLEAR
    //FLAG_ONGOING_EVENT 表示该通知通知放置在正在运行,不能被手动清除,但能通过 cancel() 方法清除
    //等价于 builder.setOngoing(true);
     */
    //notification.flags = Notification.FLAG_ONGOING_EVENT
    //发送通知请求
    manager?.notify(notifyId, notification)
    return manager!!

}

@RequiresApi(Build.VERSION_CODES.JELLY_BEAN)
@Deprecated("use createNotification(smallIcon,notifyId,channelId,action)")
fun Context.createNotification(smallIcon: Int, action: NotificationModel.() -> Unit): NotificationManager {
    val model = NotificationModel()
    action(model)

    val manager = notificationManager

    val mBuilder: Builder
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

        if (model._channelId.isEmpty()) throw NullPointerException("_channelId is empty")
        if (model._channeName.isEmpty()) throw NullPointerException("_channeName is empty")

        mBuilder = Builder(this, model._channelId)

        val channel = NotificationChannel(model._channelId, model._channeName, NotificationManager.IMPORTANCE_DEFAULT)
        //呼吸灯 Enable
        channel.enableLights(model._enable_lights)
        if (model._enable_lights) {
            channel.lightColor = Color.RED
        }
        //震动 Enable
        channel.enableVibration(model._enable_vibration)
        if (model._enable_vibration) {
            if (model._vibrationPattern != null) {
                channel.vibrationPattern = model._vibrationPattern//longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
            }
        }
        if (model._sound != null) {
            channel.setSound(model._sound, Notification.AUDIO_ATTRIBUTES_DEFAULT)
        }

        if (model.group.isNotEmpty()) {
            channel.group = model.group
        }
        manager?.createNotificationChannel(channel)

    } else {
        mBuilder = Builder(this)
        //设置通知方式，声音，震动，呼吸灯等效果，这里通知方式为声音
        mBuilder.setDefaults(Notification.DEFAULT_LIGHTS)
    }

    //设置最小图标
    mBuilder.setSmallIcon(smallIcon)
    //点击后自动删除通知
    mBuilder.setAutoCancel(model._autoCancel)


    //region 设置自定义 UI 的话
    if (model._layoutId != 0) {
        val remoteView = RemoteViews(packageName, model._layoutId)
        model._remoteView = remoteView
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            mBuilder.setCustomContentView(remoteView)
        } else {
            mBuilder.setContent(remoteView)
        }


        model._bindProgress.forEach {
            remoteView.setProgressBar(it.key, it.value.max, it.value.progress, it.value.indeterminate)
        }
        model._bindTexts.forEach {
            val i = it.key
            val s = it.value
            remoteView.setTextViewText(i, s)
        }
        model._bindImages.forEach {
            val i = it.key
            val image = it.value
            when (image) {
                is Int -> {
                    remoteView.setImageViewResource(i, image)
                }
                is Uri -> {
                    remoteView.setImageViewUri(i, image)
                }
                is Bitmap -> {
                    remoteView.setImageViewBitmap(i, image)
                }

            }

        }

        model._bindClicks.forEach {
            val i = it.key
            val pendingIntent = it.value
            remoteView.setOnClickPendingIntent(i, pendingIntent)
        }


    } else {
        mBuilder.setContentTitle(model._titleText)
        mBuilder.setContentText(model._contentText)
        //设置 LargeIcon
        if (model._largeIconBitmap != null) {
            mBuilder.setLargeIcon(model._largeIconBitmap)
        } else {
            if (model._largeIconId != 0) {
                mBuilder.setLargeIcon(BitmapFactory.decodeResource(resources, model._largeIconId))
            }
        }

        //设置通知时间
        if (model._send_time != 0L) {
            mBuilder.setWhen(model._send_time)
        }
        //首次进入时显示效果
        //mBuilder.setTicker("我是测试内容")
        if (model.progressMax != -1 && model.currentProgress != -1) {
            mBuilder.setProgress(model.progressMax, model.currentProgress, model.indeterminate)
        }


    }
    //endregion


    if (model._bigContent != null) {
        mBuilder.setStyle(model._bigContent)
    }
    if (model._multiLineContent != null) {
        mBuilder.setStyle(model._multiLineContent)
    }

    if (model._bigImage != null) {
        mBuilder.setStyle(model._bigImage)
    }


    if (model._pendingIntent != null) {
        mBuilder.setContentIntent(model._pendingIntent)
    }

    val notification = mBuilder.build()


    if (model._noClear) {
        notification.flags = Notification.FLAG_NO_CLEAR
    } else {
        notification.flags = Notification.FLAG_AUTO_CANCEL
    }

    if (model.group.isNotEmpty()) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
            mBuilder.setGroup(model.group)
            mBuilder.setGroupSummary(model.groupSummary)
        }
    }

    /**
     * 设置FLAG_ONGOING_EVENT
     * 该 flag 表示发起正在运行事件（活动中）
     * //设置 Notification 的 flags = FLAG_NO_CLEAR
    //FLAG_ONGOING_EVENT 表示该通知通知放置在正在运行,不能被手动清除,但能通过 cancel() 方法清除
    //等价于 builder.setOngoing(true);
     */
    //notification.flags = Notification.FLAG_ONGOING_EVENT
    //发送通知请求
    manager?.notify(model._notifyId, notification)
    return manager!!

}

class NotificationModel {
    var _titleText = ""
    var _contentText = ""
    //大量内容显示
    var _bigContent: Notification.BigTextStyle? = null
    //多行内容(一行，一行 显示的)
    var _multiLineContent: Notification.InboxStyle? = null
    //设置发送时间
    var _send_time: Long = 0
    //大图片
    var _bigImage: Notification.BigPictureStyle? = null

    var _largeIconId = 0
    var _largeIconBitmap: Bitmap? = null
    var group = ""
    var groupSummary = false

    var notificationBuilder: Notification.Builder? = null
    fun builder(action: (Notification.Builder) -> Builder) {
        if (notificationBuilder != null)
            action(notificationBuilder!!)
    }


    //Set Progress
    internal var progressMax = -1
    internal var currentProgress = -1
    internal var indeterminate = false
    fun setProgress(max: Int, progress: Int, indeterminate: Boolean = false) {
        this.progressMax = max
        this.currentProgress = progress
        this.indeterminate = indeterminate

    }

    //点击通知后自动清除(设置PendingIntent才生效)
    var _autoCancel = true //设为 true 点击时会清除 否则(false) 不能清除
    var autoCancel = true //设为 true 点击时会清除 否则(false) 不能清除
    var _noClear = false //如果设为 true 手动不能清除 否则(false) 可手动能清除
    var noClear = false //如果设为 true 手动不能清除 否则(false) 可手动能清除
    var _notifyId = 0 //NotifyId

    var _enable_lights = false
    var _enable_vibration = false
    var _sound: Uri? = null
    var _vibrationPattern: LongArray? = null

    //Android 8.0 后添加的需求
    var _channelId = ""
    var _channeName = ""

    //使用 RemoteView 时
    var _layoutId = 0
    internal var _remoteView: RemoteViews? = null
    var _pendingIntent: PendingIntent? = null

    //Bind View
    internal var _bindTexts = HashMap<Int, String>()
    internal var _bindProgress = HashMap<Int, ProgressModel>()
    internal var _bindImages = HashMap<Int, Any>()
    internal var _bindClicks = HashMap<Int, PendingIntent>()

    /**
     * Bind Text
     */
    fun bindText(viewId: Int, text: String) {
        _bindTexts.put(viewId, text)
    }

    /**
     * Bind Progress
     */
    fun bindProgress(viewId: Int, progress: Int, max: Int = 100, indeterminate: Boolean = false) {
        _bindProgress.put(viewId, ProgressModel(progress, max, indeterminate))
    }

    /**
     * Bind Image
     */
    fun bindImage(viewId: Int, image: Int) {
        _bindImages.put(viewId, image)
    }

    fun bindImage(viewId: Int, image: Bitmap) {
        _bindImages.put(viewId, image)
    }

    fun bindImage(viewId: Int, image: Uri) {
        _bindImages.put(viewId, image)
    }

    /**
     * Bind Click
     */
    fun bindClick(viewId: Int, pendingIntent: PendingIntent) {
        _bindClicks.put(viewId, pendingIntent)
    }

    data class ProgressModel(var progress: Int, var max: Int = 100, var indeterminate: Boolean = false)
}


